﻿
using System;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Utilities.Xml
{
    public class ModelCreator<T>
    {
        public static T CreateInstanceFromXml(string modelXml)
        {
            return CreateInstanceFromXml(null, modelXml);
        }

        public static T CreateInstanceFromXml(string modelXml, string NameSpace)
        {
            T model;
            try
            {
                XmlWriterSettings writerSettings = new XmlWriterSettings();
                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add(string.Empty, string.Empty);
                writerSettings.OmitXmlDeclaration = true;

                // convert string to stream
                byte[] byteArray = Encoding.UTF8.GetBytes(modelXml);
                Stream inputStream = new MemoryStream(byteArray);

                XmlReaderSettings xrs = new XmlReaderSettings() { Async = false, CloseInput = true };
                using (XmlReader reader = XmlReader.Create(inputStream, xrs))
                {
                    XmlSerializer serialzer;
                    if (string.IsNullOrEmpty(NameSpace))
                    {
                        serialzer = new XmlSerializer(typeof(T));
                    }
                    else
                    {
                        serialzer = new XmlSerializer(typeof(T), NameSpace);
                    }
                    //serialzer.UnknownAttribute
                    model = (T)serialzer.Deserialize(reader);
                    return model;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return default(T);
            }
            finally
            {
                ////Logger.LogVerbose("Finally!");
            }
        }


        public async static Task<T> CreateInstanceFromXmlAsync(string modelXml, string NameSpace)
        {
            try
            {
                return await Task.Run(() => CreateInstanceFromXml(modelXml, NameSpace));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return default(T);
            }
        }
    }
}
